How to upload files with FormData using JavaScript 您所在的位置:网站首页 js formdata append document How to upload files with FormData using JavaScript

How to upload files with FormData using JavaScript

2023-11-07 16:32| 来源: 网络整理| 查看: 265

The FormData interface is available in all modern browsers as an HTML5 web API. It can be used to store key-value pairs representing form fields and their values.

Once you construct a FormData object, it can be easily sent to the server by using Fetch API, XMLHttpRequest or Axios.

In this article, you'll learn how to upload single or multiple files using FormData in JavaScript.

Uploading Single File

Let us say you have got the following HTML element:

Now, we want to make sure that when the user selects a file for upload, it is automatically sent to the server for processing.

Here is an example code that you can use for this purpose:

const input = document.querySelector('#avatars'); // Listen for file selection event input.addEventListener('change', (e) => { fileUpload(input.files[0]); }); // Function that handles file upload using XHR const fileUpload = (file) => { // Create FormData instance const fd = new FormData(); fd.append('avatar', file); // Create XHR rquest const xhr = new XMLHttpRequest(); // Log HTTP response xhr.onload = () => { console.log(xhr.response); }; // Send XHR reqeust xhr.open('POST', `/upload-avatar`); xhr.send(fd); }; Uploading Multiple Files

The FormData interface can also be used to upload multiple files at once. First of all, add the multiple attribute to the element to allow the user to select more than one files:

Next, modify the fileUpload() method to iterate over all selected files and add then to the FormData object:

const input = document.querySelector('#avatars'); // Listen for file selection event input.addEventListener('change', (e) => { fileUpload(input.files); }); // Function that handles file upload using XHR const fileUpload = (files) => { // Create FormData instance const fd = new FormData(); // Iterate over all selected files Array.from(files).forEach(file => { fd.append('avatar', file); }); // Create XHR rquest const xhr = new XMLHttpRequest(); // Log HTTP response xhr.onload = () => { console.log(xhr.response); }; // Send XHR reqeust xhr.open('POST', `/upload-avatar`); xhr.send(fd); };

That's it. The server will receive an array of binary files in the avatar request parameter.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有